<?php
class HQ_Db {

	private $ci;

	function HQ_Db() {
	    // For PHP4 compatibility
	    $this->__construct();
    }
    
	function __construct() {
		$this->ci =& get_instance();	
		include(APPPATH.'/config/database.php');
		$this->ci->db = $this->ci->load->database($active_group, TRUE);
        if($this->ci->db->conn_id == false) {
			$this->alert();
			$this->ci->db = $this->ci->load->database('backup', TRUE);
		};
	}

	function alert() {

		$message =
		"Message from: " .$_SERVER["HTTP_HOST"] . "<br />".PHP_EOL."
		connection failed due to: <br />" . PHP_EOL.
		mysql_error() . "<br />" . PHP_EOL."
		Error number:" . mysql_errno()  ."<br />".PHP_EOL."
		Now connecting to stage2.worldwidelearn.com<br />".PHP_EOL."
		User IP: " . $_SERVER['REMOTE_ADDR'];
        print_r($message);die;
		$this->ci->load->library('email');
		$this->ci->email->mailtype = 'html';
		$this->ci->email->from('error-report@hqpublications.com', $_SERVER["HTTP_HOST"]);
		$this->ci->email->to('HQ_Alert@quinstreet.com');
		$this->ci->email->subject('Connection to WWL failed');
		$this->ci->email->message($message);
		$this->ci->email->send();
	}

	function log_queries($type) {
		$date = date('M d, Y G:i:s');
		$data = '';

		switch($type) {
			case 'csv':

				$headers = "Date\tURI\tQuery\tExecution Time".PHP_EOL;

				foreach($this->ci->db->queries as $key => $query) {
					 $data .= $date;
					 $data .= "\t";
					 $data .= $this->ci->uri->uri_string;
					 $data .= "\t";
					 $data .= $query;
					 $data .= "\t";
					 $data .= $this->ci->db->query_times[$key];
					 $data .= PHP_EOL;
				}

				$extension = '.csv';
			break;

			case 'multi':
				$counter = 1;

				$data .= 'URI: '.$this->ci->uri->uri_string.PHP_EOL;
				$data .= 'Date: '.$date.PHP_EOL.PHP_EOL;

				foreach($this->ci->db->queries as $key => $query) {
					$data .= "Query $counter: ".	$query.PHP_EOL;
					$data .= 'Execution Time: '.$this->ci->db->query_times[$key].PHP_EOL.PHP_EOL;
					$counter++;
				}
				$data .= '------------------------------------------------------------'.PHP_EOL;

				$extension = '.txt';
			break;

			default:
				$invalid_request = TRUE;
			break;
		}

		if(!isset($invalid_request)) {
			$this->ci->load->helper('file');
			$path =  APPPATH.'logs/sql/'.date('Y-M-d').$extension;

			if($type == 'csv' && get_file_info($path, 'readable') == FALSE) {
				$data = $headers.$data;
			}
			$file = write_file($path, $data,'a');
		}
	}
}
?>